﻿Imports System.IO
Imports Training.Common

Partial Public Class AddGroup
    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    ''' <summary>
    ''' Add Group Button Click event
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>Run checks before creating account</remarks>
    Private Sub btnAddGroup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddGroup.Click
        If Page.IsValid Then
            ' check for existing elements of group & membership
            If Len(CheckItems()) <> 0 Then
                ' display error msg
                lblReturn.Text = CheckItems()
            Else
                ' checks passed, proceed with account creation
                lblReturn.Text = CreateGroup()
            End If
        Else
            lblReturn.Text = "Required Elements could not be validated. Contact Webmaster."
        End If
    End Sub

    ''' <summary>
    ''' Check GroupName,LoginName,Email address for duplicates
    ''' </summary>
    ''' <returns>Error message(s)</returns>
    ''' <remarks>use before attempting to create membership account</remarks>
    Private Function CheckItems() As String
        Dim retVal As String
        retVal = ""

        ' check groupname
        If CheckGroupName(tbGroup.Text) > 0 Then
            retVal &= "Group name is in use, please enter a different group name. "
        End If

        ' check username
        If CheckLoginName(tbLogin.Text) > 0 Then
            retVal &= " Login name is in use, please enter a different login name. "
        End If

        ' check email
        If CheckMemberEmail(tbEmail.Text) > 0 Then
            retVal &= " Email address is in use, please enter a different Email address."
        End If

        ' check password
        If Len(tbPass.Text) < 6 Then
            retVal &= " Password must be 6 characters or greater."
        End If

        Return retVal
    End Function

    ''' <summary>
    ''' Create Membership login and add group name
    ''' </summary>
    ''' <returns>CreateAccount Status and error message if applicable</returns>
    ''' <remarks>Checks prior to this function should prevent errors</remarks>
    Private Function CreateGroup() As String
        Dim retVal As String
        Dim gCount As Integer
        Dim lfile As String ' logo file

        ' check for successful logo upload
        If fuLogo.FileName <> String.Empty Or fuLogo.FileName <> "" Then
            ' we have a file name
            lfile = UploadFile()
            ' make sure file uploaded
            If lfile = String.Empty Then
                retVal = "logo upload failed, group creation aborted."
                Return retVal
                Exit Function
            End If
        Else
            lfile = String.Empty
        End If

        ' create membership account
        retVal = AddGroupLogin(tbLogin.Text, tbPass.Text, tbEmail.Text)

        ' add user to "group" role
        Roles.AddUserToRole(tbLogin.Text, "group")

        ' lookup userid for group to associate login with group
        Dim user As MembershipUser = Membership.GetUser(tbLogin.Text)
        Dim uid As String = user.ProviderUserKey.ToString()

        ' add group name
        gCount = AddGroupAccount(tbGroup.Text, uid, lfile)
        If gCount > 0 Then
            retVal &= " Error adding GroupName. Error has been logged."
        Else
            ' add initial module "All Users" for group
            ' step 1 get groupid
            Dim gid As Integer
            gid = GetGroupIDByMembershipID(uid)
            ' step 2 add module for group
            If AddGroupModule(gid, 1) > 0 Then
                log.Error("ERROR * Adding Initial Group Module Failed for GroupID: " & gid)
            End If
        End If

        Return retVal
    End Function

    ''' <summary>
    ''' Clear all fields and reset values
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>Values are not cleared on Add button click, this resets form</remarks>
    Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        tbGroup.Text = String.Empty
        tbLogin.Text = String.Empty
        tbPass.Text = String.Empty
        tbPConf.Text = String.Empty
        tbEmail.Text = String.Empty
        tbEConf.Text = String.Empty
        lblReturn.Text = String.Empty
    End Sub

    ''' <summary>
    '''  upload the logo file
    ''' </summary>
    ''' <remarks></remarks>
    Private Function UploadFile() As String
        Dim logo As String
        Dim fn As String ' file name
        Dim ct As String ' file content
        Dim fz As String ' file size
        Dim fileUploaded As Boolean

        ' initial value of fileUploaded
        fileUploaded = False

        fn = fuLogo.PostedFile.FileName
        ct = fuLogo.PostedFile.ContentType
        fz = fuLogo.PostedFile.ContentLength

        ' define path to upload folder
        Dim p As String
        p = Server.MapPath("../images/logos")

        Try
            ' upload the actual file
            fuLogo.PostedFile.SaveAs(p & "\" & System.IO.Path.GetFileName(fn.ToString()))
            ' set fileUploaded
            fileUploaded = True

            ' check if upload completed
            If fileUploaded Then
                ' get file type and path
                logo = System.IO.Path.GetFileName(fn.ToString())
            Else
                ' upload failed, notify user
                logo = String.Empty
            End If
        Catch ex As Exception
            ' also log error here
            log.Error("Error uploading logo * " & ex.ToString)
            logo = String.Empty
        End Try

        Return logo
    End Function
End Class